package leetcode.code1813;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public boolean areSentencesSimilar(String sentence1, String sentence2) {
		int len1 = sentence1.length();
		int len2 = sentence2.length();
		if (len1 == len2) {
			return sentence1.equals(sentence2);
		}
		String[] words1 = len1 > len2 ? sentence1.split(" ") : sentence2.split(" ");
		String[] words2 = len1 > len2 ? sentence2.split(" ") : sentence1.split(" ");
		return this.prefix(words1, words2) || this.suffix(words1, words2) || this.other(words1, words2) ? true : false;
	}

	private boolean prefix(String[] words1, String[] words2) {
		for (int i = 0; i < words2.length; i++) {
			if (!words1[i].equals(words2[i])) {
				return false;
			}
		}
		return true;
	}

	private boolean suffix(String[] words1, String[] words2) {
		for (int i = words2.length - 1, j = words1.length - 1; i >= 0; i--, j--) {
			if (!words1[j].equals(words2[i])) {
				return false;
			}
		}
		return true;
	}

	private boolean other(String[] words1, String[] words2) {
		int p = 0;
		while (p < words2.length) {
			if (!words1[p].equals(words2[p])) {
				break;
			}
			p++;
		}
		int rest = words2.length - p;
		int q = words2.length - 1;
		int k = words1.length - 1;
		while (q >= words2.length - rest) {
			if (!words1[k].equals(words2[q])) {
				break;
			}
			k--;
			q--;
		}
		return q == words2.length - rest - 1;

	}

	@Override
	public void debug4() {
		H.compare(true, this.areSentencesSimilar("My name is Haley", "My Haley"));
		H.compare(true, this.areSentencesSimilar("My name is Haley", "My name"));
		H.compare(true, this.areSentencesSimilar("My name is Haley", "is Haley"));
		H.compare(false, this.areSentencesSimilar("My name is Haley", "My is"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
